<template>
  <div id="todolist">
    <div class="tit">
      <h1>自律一下</h1>
      <input type="text" placeholder="添加新的待办事项" v-model="newTodoTitle" @keyup.enter="addTodo">
      <button @click="addTodo">添加</button>
    </div>
    <div v-for="(todo, index) in todos" :key="index">
      <TodoItem :title="todo.title" :completed="todo.completed" @update:completed="updateTodoCompleted($event, index)" @remove-todo="removeTodo(index)"></TodoItem>
    </div> 
  </div>
</template>

<script>
  import TodoItem from './TodoItem.vue';
  export default {
    components: {
      TodoItem  //子组件
    },
    data(){
      return{
        todos:[{
          title: '复习计算机知识', 
          completed: false
        }],  //待办事项数组
        newTodoTitle:''  //用户输入的新待办事项标题
      }
    },
    methods: {
      // 添加一个新的待办事项到todos数组
      addTodo() {
        if (this.newTodoTitle.trim()) {
          this.todos.push({ 
            title: this.newTodoTitle, 
            completed: false 
          });
          this.newTodoTitle = '';
        }
      },
      // 从todos数组中删除一个待办事项
      removeTodo(index) {
        this.todos.splice(index, 1);
      },
      // 更新待办事项的完成状态
      updateTodoCompleted(completed, index) {
        this.todos[index].completed = completed;
        }
    }
  }
</script>

<style lang="less" scoped>
  #todolist{
    width: 300px;
    height: 400px;
    margin: 0 auto;
    .tit{
      margin-bottom: 10px;
      text-align: center;
      input{
        width: 180px;
        margin-right: 5px;
      }
    }
  }
</style>